// pages/order/index.js
const app = getApp()
const wxpay = require('../../utils/pay.js')
const dateUtil = require('../../utils/date.js')
const CONFIG = require('../../config.js')
const WXAPI = require('../../wxapi/main')
const CryptoJS = require('../../utils/crypto.js')

import drawQrcode from '../../utils/weapp.qrcode.min.js'
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    templateList:[],
    interval:null,
    select:null
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    this.setData({
      userInfo: wx.getStorageSync("userInfo")
    })
    this.queryRechargeTemplateList();
  },
  queryRechargeTemplateList(){
    WXAPI.queryRechargeTemplateList().then(res=>{
        this.setData({
          templateList:res
        })
    })
  },
  select:function(e){
    var data=e.currentTarget.dataset.data;
    this.setData({
      select:data
    })
  },
  pay: async function() {
    var data=this.data.select;
    if(!data){
      wx.showToast({
        "title":"请选择一个充值"
      });
    }
    
    try {
      WXAPI.recharge(data.id).then(res=>{
        if(res.code==200){
          var payment=res.data;

          wx.requestPayment({
            appid: payment.appid,
            timeStamp: payment.timeStamp,
            nonceStr: payment.nonceStr,
            package: payment.package,
            signType: payment.signType,
            paySign: payment.paySign,
            success:(res)=> {
              wx.showToast({
                "title":"订单支付成功"
              });
            },
            fail:(res)=> {
              console.log(res)
            }
          });
          
          var interval=setInterval(()=>{
            WXAPI.queryOrderByNo(payment.order_no).then(res=>{
              if(res.status==2){
               clearInterval(this.data.interval)
               wx.showToast({
                 "title":"订单支付成功"
               });
               app.refreshData((userInfo)=>{
                 this.setData({
                   userInfo
                 })
               });
              }
           })
          },100)
          this.setData({
             interval
          })
      }else{
        Toast({
          context: this,
          selector: '#t-toast',
          message: "订单支付失败:"+(res.message || res.msg),
        });
      }
        
    })
    } catch (error) {
    }
  }
})
